package umg.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;

import umg.vo.TwoStrings;

import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;

public class CountryLookup
{
	static LookupService db = null;
	final String DBPATH = "GeoLiteCity.dat";
	private static HashMap<String, TwoStrings> locationCache;
	final static String FLAGPATH = "flags/";
	final static String EXT = ".gif";
	final static String DEFAULTFLAG = "-";
	public final static String UNK = "Unknown";

	public String getDatabaseInfo()
	{
		if (db == null) return null;
		else
		{
			return db.getDatabaseInfo().toString();
		}
	}

	public CountryLookup()
	{
		if (db == null)
		{
			try
			{
				db = new LookupService(DBPATH, LookupService.GEOIP_MEMORY_CACHE);
			}
			catch (Exception e)
			{
				System.out.println("Error opening GeoIP database file:" + DBPATH);
				//e.printStackTrace();
			}
		}

		if (locationCache == null)
		{
			locationCache = new HashMap<String, TwoStrings>(1000);
		}
	}

	String defaultFlag = FLAGPATH + DEFAULTFLAG + EXT;

	public TwoStrings locate(String ip)
	{
		//first check the cache.
		if (locationCache != null)
		{
			TwoStrings cacheResult = locationCache.get(ip);
			if (cacheResult != null) return cacheResult;
		}

		TwoStrings country = new TwoStrings();//path, name
		Location l = null;

		if (db != null && ip != null && ip.length() > 0)
		{
			try
			{
				l = db.getLocation(ip);
			}
			catch (Exception e)
			{
				if (PropertyManager.isDebug()) System.out.println("Could not locate IP:" + ip);
			}
		}

		if (l != null)
		{//found
			country.setValue1(FLAGPATH + l.countryCode.toLowerCase() + EXT);
			country.setValue2(l.countryName);
		}
		else
		{//not found
			country.setValue1(defaultFlag);
			country.setValue2(UNK);
		}

		//add to the cache (success and failure)
		if (locationCache != null)
		{
			locationCache.put(ip, country);
		}

		return country;
	}

	public static void main(String[] args)
	{
		CountryLookup c = new CountryLookup();
		TwoStrings result;
		result = c.locate("65.220.10.3");
		System.out.println("Flag path=" + result.getValue1() + " Country=" + result.getValue2());

		result = c.locate("189.220.10.3");
		System.out.println("Flag path=" + result.getValue1() + " Country=" + result.getValue2());

		result = c.locate("1.220.10.3");
		System.out.println("Flag path=" + result.getValue1() + " Country=" + result.getValue2());

		result = c.locate(null);
		System.out.println("Flag path=" + result.getValue1() + " Country=" + result.getValue2());

	}

	//get all countries
	public void getCountries(Connection conn)
	{
		// System.out.println("Running Search By name");
		Statement st = null;
		ResultSet rs = null;
		HashMap<String, Integer> countries = new HashMap<String, Integer>(160);
		try
		{
			st = conn.createStatement();
			// run the query
			rs = st.executeQuery("select ip from PLAYERS_MEM");
			String ip;
			CountryLookup c = new CountryLookup();
			TwoStrings result;
			Integer count;
			String country;
			for (; rs.next();)
			{
				// process each row
				ip = rs.getString(1);
				result = c.locate(ip);
				if (result != null && result.getValue2() != null)
				{
					if (countries.get(result.getValue2()) != null)
					{
						//exists, increment count
						country = result.getValue2();
						count = countries.get(country);
						if (count == null || count.intValue() == 0)
						{
							count = new Integer(1);
						}
						else
						{
							count++;
						}
						countries.put(country, count);//update
					}
					else
					{//new country
						countries.put(result.getValue2(), new Integer(1));
					}
				}
			}
			System.out.println("Completed getting country count");
			TreeSet<String> tree = new TreeSet<String>(countries.keySet());
			Iterator<String> it = tree.iterator();
			int countryplayers;
			while (it.hasNext())
			{
				country = (String) it.next();
				countryplayers = countries.get(country);
				System.out.println(country + " " + countryplayers);
			}
			st.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
}
